﻿/*----------------------------------------------------------------
//  <copyright file="ClaimsBasedAuthorizationFilter.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2024-03-04 14:51</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Hangfire.Dashboard.Authorization
{
    #region "表示基于声明的Hangfire授权筛选器"
    /// <summary>
    /// 表示基于声明的Hangfire授权筛选器
    /// </summary>
    public class ClaimsBasedAuthorizationFilter : IDashboardAuthorizationFilter
    {
        /// <summary>
        /// 类型
        /// </summary>
        private readonly string _type;
        /// <summary>
        /// 值
        /// </summary>
        private readonly string _value;

        #region "构造函数"
        #region "初始化一个基于声明的Hangfire授权筛选器的新实例"
        /// <summary>
        /// 初始化一个基于声明的Hangfire授权筛选器 <see cref="ClaimsBasedAuthorizationFilter"/> 的新实例
        /// </summary>
        /// <param name="type">声明类型</param>
        /// <param name="value">声明值</param>
        public ClaimsBasedAuthorizationFilter(string type, string value)
        {
            _type = type ?? throw new ArgumentNullException(nameof(type));
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }
        #endregion

        #endregion

        #region "方法"
        #region "授权"
        /// <summary>
        /// 授权
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public bool Authorize(DashboardContext context)
        {
            HttpContext httpContext = context.GetHttpContext();
            ClaimsPrincipal principal = httpContext.User;
            if (principal.Identity is not ClaimsIdentity identity)
            {
                return false;
            }
            if (identity == null)
            {
                return false;
            }
            return identity.HasClaim(_type, _value);
        }
        #endregion

        #endregion

    }
    #endregion

}
